package com.jxt.mina.tools;

import java.nio.charset.Charset;

import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;


/**
 * @author Scott.Wong
 * 解码器
 */
public class CodecDecoder implements ProtocolDecoder{
   
	private Logger logger = Logger.getLogger(CodecDecoder.class);
	private Charset charset = Charset.forName("UTF-8");
	private IoBuffer ioBuffer = IoBuffer.allocate(1024).setAutoExpand(true);
	public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
			throws Exception {
		logger.info("开始解码");
		while(in.hasRemaining()){
			byte by = in.get();
			ioBuffer.put(by);
			if(by == '\n'){
				ioBuffer.flip();
				byte[] b = new byte[ioBuffer.limit()];
				ioBuffer.get(b);
				String msg = new String(b,charset);
				ioBuffer = IoBuffer.allocate(100).setAutoExpand(true);
				out.write(msg);
			}
		}
	}

	public void dispose(IoSession arg0) throws Exception {		
	}

	public void finishDecode(IoSession arg0, ProtocolDecoderOutput arg1)
			throws Exception {
		logger.info("解码已完成......");
	}

}
